<?php
/**
 * 公共缓存读取函数
 * Class cache
 */
class cache {

	var $db;
	var $cachefile;

	function __construct(& $db) {
		$this->db = $db;
	}

	/**
	 * 文件是否可用
	 * @param $cachename
	 * @param $cachetime
	 * @return bool
	 */
	public function isvalid($cachename, $cachetime) {
		$this->_getfile($cachename);
		if (!is_readable($this->cachefile) || $cachetime < 0) {
			return false;
		}
		if (0 == $cachetime) {
			return true;
		}
		clearstatcache();
		return (time() - filemtime($this->cachefile)) < $cachetime;
	}

	/**
	 * 获取缓存的内容
	 * @param     $cachename
	 * @param int $cachetime
	 * @return bool|mixed
	 */
	public function getcache($cachename, $cachetime = 0) {
		if ($this->isvalid($cachename, $cachetime)) {
			return include $this->cachefile;
		}
		return false;
	}

	/**
	 * 写入缓存
	 * @param $cachename
	 * @param $arraydata
	 * @return int|void
	 */
	public function writecache($cachename, $arraydata) {
		$this->_getfile($cachename);
		$data    = is_array($arraydata) ? var_export($arraydata, true) : "'" . $arraydata . "'";
		$strdata = "<?php\nreturn " . $data . ";\n?>";
		$bytes   = file::writetofile($this->cachefile, $strdata);
		return $bytes;
	}

	/**
	 * 移除缓存
	 * @param $cachename
	 */
	public function removecache($cachename) {
		$this->_getfile($cachename);
		if (file_exists($this->cachefile)) {
			unlink($this->cachefile);
		}
	}

	/**
	 * 读取缓存，如果缓存不存在则自动创建并返回
	 * @param     $cachename
	 * @param int $available    数据库缓存的可用性
	 * @return array|bool|mixed
	 */
	public function load($cachename, $available = 0) {
		$arraydata = $this->getcache($cachename);
		if (!$arraydata) {
			$arraydata = array();
			$sql       = "SELECT * FROM " . DB_TABLEPRE . $cachename;
			if ($available) {
				$sql = $sql . "  WHERE  available=1";
			}
			if ('channel' == $cachename) {
				$sql = $sql . "  ORDER BY displayorder ASC";
			}
			$query = $this->db->query($sql);
			if (!$query) {
				return false;
			}
			while ($data = $this->db->fetch_array($query)) {
				if ($available) {
					$arraydata[] = $data;
				} else {
					if (isset($data['variable'])) {
						$arraydata[$data['variable']] = $data['value'];
					} else {
						$arraydata[$data['find']] = $data['replacement'];
					}
				}
			}
			if ('setting' == $cachename) { //兼容以前版本的插件
				$arraydata['site_url'] = WIKI_URL;
			}
			$this->writecache($cachename, $arraydata);
		}
		return $arraydata;
	}



	/**
	 * 完善缓存的名称
	 * @param $cachename
	 */
	private function _getfile($cachename) {
		$this->cachefile = HDWIKI_ROOT . '/data/cache/' . $cachename . '.php';
	}
}